package com.jay.media.music.ui.music

import android.media.browse.MediaBrowser
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.PopupMenu
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavOptions
import com.jay.base.ui.BaseFragment
import com.jay.media.kit.LogHelper
import com.jay.media.music.core.provider.MusicIDHelper
import com.jay.media.music.ui.HomeActivity
import com.jay.media.music.ui.R
import com.jay.media.music.ui.base.FragmentBackHandler
import com.jay.media.music.ui.databinding.FragmentMusicBinding
import com.jay.media.music.ui.manager.MusicClientManager

class MusicFragment : BaseFragment(), MediaAdapter.OnItemClickListener, FragmentBackHandler {

    companion object {
        const val TAG_MEDIA_FRAGMENT = "tag_media_fragment"
        const val KEY_PARENT_ID = "KEY_PARENT_ID"

        fun newInstance(parentId: String): MusicFragment {
            val musicFragment = MusicFragment()
            val bundle = Bundle()
            bundle.putString(KEY_PARENT_ID, parentId)
            musicFragment.arguments = bundle
            return musicFragment
        }
    }

    private lateinit var mediaViewModel: MediaViewModel
    private var _binding: FragmentMusicBinding? = null

    private val binding get() = _binding!!
    private var parentId: String? = null

    override fun rootView(container: ViewGroup?): View? {
        Log.d(TAG, "rootView() called")
        mediaViewModel =
            ViewModelProvider(this).get(MediaViewModel::class.java)

        _binding = FragmentMusicBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onDestroyView() {
        LogHelper.d(TAG, "onDestroyView() called")
        super.onDestroyView()
        _binding = null
    }

    override fun initData() {
        parentId = arguments?.getString(KEY_PARENT_ID)
        navigateToBrowser(parentId)
    }

    private fun navigateToBrowser(item: MediaBrowser.MediaItem?) {
        navigateToBrowser(item?.mediaId, item?.description?.subtitle as String?)
    }

    private fun navigateToBrowser(
        mediaId: String?,
        subTitle: String? = getString(R.string.menu_music)
    ) {
        Log.d(TAG, "navigateToBrowser() called with: mediaId = $mediaId, subTitle = $subTitle")
        val browserFragment = childFragmentManager.findFragmentByTag(TAG_MEDIA_FRAGMENT + mediaId)
        if (browserFragment == null || (browserFragment as MusicBrowserFragment).getMediaId() != mediaId) {
            val mediaBrowserFragment = MusicBrowserFragment.createInstance(
                mediaId, subTitle.toString(), this
            )
            val transaction = childFragmentManager.beginTransaction()
            transaction.replace(
                R.id.media_list_fragment,
                mediaBrowserFragment,
                TAG_MEDIA_FRAGMENT + mediaId
            )
            if (mediaId != parentId) {
                transaction.addToBackStack(mediaId)
            }
            transaction.commit()
        }
    }

    override fun onItemClick(view: View, item: MediaBrowser.MediaItem) {
        if (item.isPlayable) {
            MusicClientManager.getClient().playFromMediaId(item.mediaId)
            toPlayFragment()
        } else if (item.isBrowsable) {
            navigateToBrowser(item)
        }
    }

    private fun toPlayFragment() {
        val navOptions = NavOptions.Builder()
            .setEnterAnim(R.anim.bottom_up_anim)
            .setPopExitAnim(R.anim.up_bottom_anim)
            .setLaunchSingleTop(true)
            .build()
        val homeActivity = mActivity as HomeActivity
        homeActivity.navigate(R.id.nav_play, null, navOptions)
    }

    override fun onItemMenuClick(view: View, position: Int, item: MediaBrowser.MediaItem) {
        val popupMenu = PopupMenu(mActivity, view, Gravity.BOTTOM)
        popupMenu.inflate(R.menu.menu_music_browser)
        popupMenu.setOnMenuItemClickListener {
            when (it.itemId) {
                R.id.action_add_playlist -> {
                    MusicClientManager.getClient().operatePlayList(
                        MusicIDHelper.extractMusicIDFromMediaID(item.mediaId!!),
                        true
                    )
                    true
                }
                else -> true
            }
        }
        popupMenu.show()
    }

    override fun onBackPressed(): Boolean {
        return childFragmentManager.popBackStackImmediate()
    }
}